# rsstoatom.py
# Original Author: Amar Zumkhawala (amarzumkhawala@gmail.com)
# Project URL - http://code.google.com/p/feedflare-categories
# Distributed under Apache License 2.0
#
# $Revision: 7 $, $Date: 2008-12-28 01:00:43 -0500 (Sun, 28 Dec 2008) $
# $Author: amarzumkhawala $

from atom import AtomEntry
from xml.dom.minidom import parseString
from xml.dom.minidom import getDOMImplementation
from xmlutil import getText
import logging

"""
A Simple RSS xml To Atom xml Converter Class.  Only handles a few critical tags.
"""
class RssToAtom:
  def isRss(self, xml):
    rss = xml.find("<rss")
    return (rss > 0)

  def convert(self, xml):
    impl = getDOMImplementation()
    atomdom = impl.createDocument(None,"feed",None)
    feedelement = atomdom.documentElement
    rssdom = parseString(xml)
    items = rssdom.getElementsByTagName("item")
    for item in items:
      entry = atomdom.createElement("entry")
      feedelement.appendChild(entry)
      
      # convert rss category tag to atom 
      itemCategories = item.getElementsByTagName("category")
      for itemCategory in itemCategories:
        category = atomdom.createElement("category")
        entry.appendChild(category)
        term = getText(itemCategory)
        category.setAttribute("term", term)
          
      # convert rss guid tag to a link & id tag
      itemGuids = item.getElementsByTagName("guid")
      for itemGuid in itemGuids:
        link = atomdom.createElement("link")
        entry.appendChild(link)
        url = getText(itemGuid).strip()
        link.setAttribute("rel","alternate")
        link.setAttribute("href",url)         

        id = atomdom.createElement("id")
        entry.appendChild(id)
        text = atomdom.createTextNode(url)
        id.appendChild(text)

    atomxml = feedelement.toxml()
    return atomxml
